package mamikeji.liaowa.ui.activity.forum;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.UploadImageBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.circle.PreviewViewPagerActivity;
import mamikeji.liaowa.ui.adapter.CircleImageAdapter;
import mamikeji.liaowa.utils.FileUtils;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MaxTextLength;
import mamikeji.liaowa.utils.SystemUtils;
import mamikeji.liaowa.widget.CustomGridView;
import mamikeji.liaowa.widget.selectorImage.MultiImageSelector;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PublishForumActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_CAMERA = 100;
    private static final int REQUEST_GALLERY = 101;
    private static final int REQUEST_PREVIEW = 102;
    private static final int MAX_IMAGE = 9;
    @BindView(R.id.editText_publish_forum_title)
    EditText editTextPublishForumTitle;
    @BindView(R.id.et_publish_forum_input)
    EditText etPublishForumInput;
    @BindView(R.id.tv_publish_forum_hint)
    TextView tvPublishForumHint;
    @BindView(R.id.gv_publish_forum_image)
    CustomGridView gvPublishForumImage;

    private CircleImageAdapter adapter;
    private Dialog dialog;
    private String mImageFileName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_forum);
        ButterKnife.bind(this);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.publish_forum_name);
        setTitleRightBtn(R.string.publish_circle_right, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(editTextPublishForumTitle.getText().toString())) {
                    ForToast.showToast("请输入标题！");
                    return;
                }
                if (TextUtils.isEmpty(etPublishForumInput.getText().toString())) {
                    ForToast.showToast("请输入内容！");
                    return;
                }
                List<File> selectedImageList = adapter.getSelectedImageList();
                if (selectedImageList != null && selectedImageList.size() > 0) {//有图片
                    compress(selectedImageList);
                } else {//没图片
                    String content = etPublishForumInput.getText().toString().trim();
                    String title = editTextPublishForumTitle.getText().toString().trim();
                    publicForum(title, content, "", "1");
                }
            }
        });

        String lengthString = getResources().getString(R.string.publish_length);
        String lengthFinal = String.format(lengthString, 0);
        tvPublishForumHint.setText(lengthFinal);

        init();
    }

    private void init() {
        gvPublishForumImage.setSelector(new ColorDrawable(Color.TRANSPARENT));
        etPublishForumInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String lengthString = getResources().getString(R.string.publish_length);
                String lengthFinal = String.format(lengthString, charSequence.length());
                tvPublishForumHint.setText(lengthFinal);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        InputFilter[] filters = new InputFilter[]{new MaxTextLength(4000)};
        etPublishForumInput.setFilters(filters);

        InputFilter[] filter_tile = new InputFilter[]{new MaxTextLength(76)};
        editTextPublishForumTitle.setFilters(filter_tile);

        adapter = new CircleImageAdapter(this);
        gvPublishForumImage.setAdapter(adapter);
        adapter.setOnItemClickListener(new CircleImageAdapter.OnItemClickListener() {
            @Override
            public void onClickPreviewImage(List<String> imageList, int position) {
                Intent intent = new Intent(PublishForumActivity.this, PreviewViewPagerActivity.class);
                intent.putExtra("position", position);
                intent.putStringArrayListExtra("imageList", (ArrayList<String>) imageList);
                startActivityForResult(intent, REQUEST_PREVIEW);
            }

            @Override
            public void onClickAddImage(View view, int position) {
                showPopupWindow();
            }
        });
    }

    private void showPopupWindow() {
        isKeyboardShownToHideKeyboard(etPublishForumInput);
        isKeyboardShownToHideKeyboard(editTextPublishForumTitle);

        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_circle_img, null);

        Button btn_circle_camera = (Button) inflate.findViewById(R.id.btn_circle_camera);
        Button btn_circle_album = (Button) inflate.findViewById(R.id.btn_circle_album);
        Button btn_circle_cancel = (Button) inflate.findViewById(R.id.btn_circle_cancel);

        btn_circle_camera.setOnClickListener(this);
        btn_circle_album.setOnClickListener(this);
        btn_circle_cancel.setOnClickListener(this);

        dialog.setContentView(inflate);
        dialog.show();
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;
        lp.width = (int) getResources().getDisplayMetrics().widthPixels - 30; // 宽度
        dialogWindow.setAttributes(lp);
    }

    private void pickImage() {
        MultiImageSelector.create(this)
                .showCamera(false) // 是否显示相机. 默认为显示
                .count(MAX_IMAGE) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                .multi() // 多选模式, 默认模式;
                .origin(adapter.getSelectedList()) // 默认已选择图片. 只有在选择模式为多选时有效
                .start(this, PublishForumActivity.REQUEST_GALLERY);
    }

    private void isKeyboardShownToHideKeyboard(EditText editText) {
        if (SystemUtils.isKeyboardShown(editText.getRootView())) {
            SystemUtils.hideKeyboard(this, editText.getApplicationWindowToken());
        }
    }

    public void photo() {
        // 随机缓存照片名
        mImageFileName = FileUtils.getFileNameForSystemTime(".jpg");
        // 首先判断SD卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mImageFileName)));
            startActivityForResult(intent, REQUEST_CAMERA);
        } else {
            ForToast.showToast("内存卡不存在");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_circle_camera:// 拍照
                dialog.dismiss();
                photo();
                break;
            case R.id.btn_circle_album:// 相册
                dialog.dismiss();
                pickImage();
                break;
            case R.id.btn_circle_cancel:// 取消
                dialog.dismiss();
                break;
        }
    }

    private void uploadImage(List<File> selectedImageList) {
        showLoading();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        for (File file : selectedImageList) {
            builder.addFormDataPart("file", "file.jpg", RequestBody.create(MultipartBody.FORM, file));
        }
        MultipartBody body = builder.build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(HttpApi.ROOT_PATH + HttpApi.UPLOAD_IMAGE)
                .post(body)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("失败:" + e.toString());
                hideLoading();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                UploadImageBean uploadImageBean = new Gson().fromJson(json, UploadImageBean.class);
                if (uploadImageBean.getStatus() == 200) {
                    List<UploadImageBean.ListEntity> imageList = uploadImageBean.getList();
                    if (imageList != null && imageList.size() > 0) {
                        StringBuffer imagePath = new StringBuffer();
                        for (int i = 0; i < imageList.size(); i++) {
                            if (i == imageList.size() - 1) {
                                imagePath.append(imageList.get(i).getFileUrl());
                            } else {
                                imagePath.append(imageList.get(i).getFileUrl() + ",");
                            }
                        }
                        String content = etPublishForumInput.getText().toString().trim();
                        String title = editTextPublishForumTitle.getText().toString().trim();
                        publicForum(title, content, imagePath.toString(), "3");
                    }
                }
            }
        });

    }

    private void publicForum(String title, String content, String imagePath, String type) {
        ForLog.i("publicForum","title:"+title+"\ncontent:"+content+"\nimagePath:"+imagePath+"\ntype:"+type);
        Map<String, String> formMap = new HashMap<>();
        formMap.put("fc_Titile", title);
        formMap.put("fc_Content", content);
        formMap.put("fc_ContentType", type);//朋友圈内容类型 1文字 2图片 3图品文字 ,
        formMap.put("fc_UserId", ForPreference.getString(ForContents.USER_CODE));
        formMap.put("fc_ImageUrl", imagePath);
        formMap.put("fc_Type", "1");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.SaveTopicPraise, formMap, new StringCallback() {
            @Override
            public void onError(com.squareup.okhttp.Request request, Exception e) {
                ForLog.i("dslakfj", "" + e.toString());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i("dslakfj", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ForToast.showToast("发布成功");
                        //用户话题数量
                        int num = ForPreference.getInt(ForContents.USER_forum_num) + 1;
                        //用户话题数量
                        ForPreference.putInt(ForContents.USER_forum_num, num);
                        setResult(RESULT_OK, new Intent());
                        finish();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void compress(List<File> fileList) {
        Luban.compress(this, fileList)
                .putGear(Luban.CUSTOM_GEAR)
                .setMaxSize(300)
                .launch(new OnMultiCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(List<File> fileList) {
                        uploadImage(fileList);
                    }

                    @Override
                    public void onError(Throwable e) {
                        ForToast.showToast("压缩失败");
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_GALLERY) {
                List<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                adapter.addImageList(mSelectPath);
            } else if (requestCode == REQUEST_CAMERA) {
                File file = new File(Environment.getExternalStorageDirectory() + "/" + mImageFileName);
                adapter.addImage(file.getPath());
            } else if (requestCode == REQUEST_PREVIEW) {
                List<String> imageList = data.getStringArrayListExtra("imageList");
                adapter.addImageList(imageList);
            }
        }

    }
}
